import {
  LogoutOutlined,
  LockOutlined,
  VerticalAlignBottomOutlined,
  AndroidOutlined,
  AlertOutlined,
  PaperClipOutlined,
  ApiOutlined,
  InfoCircleOutlined,
} from '@ant-design/icons';
import { useIntl, useModel, setLocale } from '@umijs/max';
import { Modal, Spin, message } from 'antd';
import type { MenuInfo } from 'rc-menu/lib/interface';
import React, { useCallback, useEffect, useState } from 'react';
import { flushSync } from 'react-dom';
import HeaderDropdown from '../HeaderDropdown';
import { createStyles } from 'antd-style';
import { ModalForm, ProFormText } from '@ant-design/pro-components';
import {
  RegisterIssuer,
  getdownload,
  postMemberUpdatePwd,
  uselogout,
  downloadFile,
} from './request';
import { getId, removeId, removeLock, removeToken } from '@/utils/token';
import './index.less';
import { useDeleteConfirm } from '@/hooks/useAlartMolder';
import { CleanCard, ReadCardIssuer } from '@/utils/Send';

export type GlobalHeaderRightProps = {
  menu?: boolean;
  children?: React.ReactNode;
  setclientid: (clientid: string) => void;
  setTimer: (Timer: string) => void;
  setVeson: (Veson: string) => void;
  setStatus: (Status: boolean) => void;
};

const useStyle = createStyles(({ token }) => ({
  main: {
    display: 'flex',
    height: '48px',
    marginLeft: 'auto',
    overflow: 'hidden',
    alignItems: 'center',
    padding: '0 8px',
    cursor: 'pointer',
    borderRadius: token.borderRadius,
    '&:hover': {
      backgroundColor: token.colorBgTextHover,
    },
  },
}));

export const AvatarName = () => {
  const data = JSON.parse(localStorage.getItem('userInfo') || '');
  return <span>{data.realName || data.username}</span>;
};
export const AvatarDropdown: React.FC<GlobalHeaderRightProps> = ({
  children,
  setclientid,
  setTimer,
  setVeson,
  setStatus,
}) => {
  // console.log("App.tsx==>"+num);
  const intl = useIntl();
  const { styles } = useStyle();

  /**
   * 退出登录
   */
  const loginOut = async () => {
    removeToken();
    removeId();
    removeLock();
    window.location.replace('/login');
  };

  const [downObj, setdownObj] = useState<any>({});
  const GetDownload = async () => {
    let { data } = await getdownload();
    setdownObj({ ...data });

    let card = await ReadCardIssuer();
    if (card.result != 0) return;
    console.log(card);
    setclientid(card.clientid);
    setTimer(card.overtime);
    setVeson(card.dllver);
    setStatus(true);
  };
  const { initialState, setInitialState } = useModel('@@initialState');
  if (!initialState) {
    return (window.location.href = '/NoInternet');
  }
  useEffect(() => {
    if (initialState.currentUser.access.length == 1) {
      var a: any = document.getElementsByClassName('ant-pro-top-nav-header-menu');
      if (a.length > 0) {
        a[0].style.opacity = '0';
      }
    }
    GetDownload();
  }, []);

  const onMenuClick = useCallback(
    async (event: MenuInfo) => {
      const { key } = event;
      if (key === 'password') {
        showModal();
        return;
      }
      if (key === 'logout' && initialState) {
        useDeleteConfirm(intl.formatMessage({ id: 'card.AWhether' }), '', async (res) => {
          if (res == true) {
            let res = await uselogout();
            if (res.code == 0) {
              flushSync(() => {
                setInitialState({ ...initialState, currentUser: undefined });
                loginOut();
              });
            }
            return;
          }
        });
      }
      if (key === 'APPdown') {
        showModalApp();
      }

      if (key === 'registered') {
        useDeleteConfirm(intl.formatMessage({ id: 'card.card issuer' }), '', async (res) => {
          if (res == true) {
            let { data } = await RegisterIssuer();
            if (data.token) {
              let data1 = {
                cardclass: 'regreader',
                uuid: 'Register your card issuer',
                serverip: data.server_ip,
                token: data.token,
              };
              // sendMessage(data1);
              // setsnedType('注册发卡器');
            }
          }
        });
        // setEnroll(true); ChangeCard
      }
      if (key === 'ChangeCard') {
        useDeleteConfirm(intl.formatMessage({ id: 'card.Clean card.' }), '', async (res) => {
          if (res == true) {
            let res = await CleanCard();
            if (res.result != 0) return message.error(res.msg);
            message.success(intl.formatMessage({ id: 'card.Cleaning successful.' }));
          }
        });
      }

      if (key === 'CN') {
        setLocale('zh-CN', true);
        localStorage.setItem('umi_locale', 'zh-CN'); // 持久化语言选择
      }
      if (key === 'US') {
        setLocale('en-US', true);
        localStorage.setItem('umi_locale', 'en-US'); // 持久化语言选择
      }
    },
    [initialState, setInitialState],
  );

  const loading = (
    <span className={styles.main}>
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8,
        }}
      />
    </span>
  );

  if (!initialState) {
    return loading;
  }

  const { currentUser } = initialState;

  if (!currentUser || !currentUser.username) {
    return loading;
  }

  const ZN = <div>cn</div>;

  const US = <div>us</div>;

  //
  const menuItems = [
    {
      key: 'APPdown',
      icon: <VerticalAlignBottomOutlined />,
      label: intl.formatMessage({ id: 'menu.APPdown' }), // 建议使用国际化 key
    },
    {
      key: 'registered',
      icon: <ApiOutlined />,
      label: intl.formatMessage({ id: 'menu.registered' }),
    },
    {
      key: 'ChangeCard',
      icon: <InfoCircleOutlined />,
      label: intl.formatMessage({ id: 'menu.ChangeCard' }),
    },
    {
      key: 'password',
      icon: <LockOutlined />,
      label: intl.formatMessage({ id: 'menu.password' }),
    },
    // {
    //   key: 'CN',
    //   icon: ZN, // 确保 ZN 是一个 React 组件
    //   label: '简体中文',
    // },
    // {
    //   key: 'US',
    //   icon: US, // 确保 US 是一个 React 组件
    //   label: 'English',
    // },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: intl.formatMessage({ id: 'components.right_content.logout' }),
    },
  ];

  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [isModalOpen, setIsModalOpen] = React.useState(false);

  const showModal = () => {
    setIsModalOpen(true);
  };

  const onFinish = async (values: any): Promise<boolean> => {
    console.log('Success:', values);
    const res: any = await postMemberUpdatePwd({
      id: getId(),
      oldPassword: values.oldPassword,
      newPassword: values.newPassword,
    });
    if (res.code !== 0) {
      message.error(res.msg);
      return false;
    }
    message.success(intl.formatMessage({ id: 'card.Password' }));
    setIsModalOpen(false);
    setTimeout(() => {
      loginOut();
    }, 500);
    return true;
  };

  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 14 },
  };
  const [AppisModalOpen, setAppisModalOpen] = useState(false);

  const showModalApp = () => {
    setAppisModalOpen(true);
  };

  const handleOk = () => {
    setAppisModalOpen(false);
  };

  const handleCancel = () => {
    setAppisModalOpen(false);
  };

  return (
    <>
      <HeaderDropdown
        menu={{
          selectedKeys: [],
          onClick: onMenuClick,
          items: menuItems,
        }}
      >
        {children}
      </HeaderDropdown>
      <ModalForm
        {...formItemLayout}

        style={{width: '500px'}}
        layout={'horizontal'}
        open={isModalOpen}
        title={intl.formatMessage({ id: 'card.Change Password' })}
        autoFocusFirstInput
        modalProps={{
         
          onCancel: () => setIsModalOpen(false),

        }}
        submitTimeout={2000}
        onFinish={onFinish}
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 20 }}
      >
        <div>
          <ProFormText.Password
            width={'md'}
            name="oldPassword"
            label={intl.formatMessage({ id: 'card.Original password' })}
            placeholder={intl.formatMessage({ id: 'card.Please enter Original' })}
            rules={[
              { required: true, message: intl.formatMessage({ id: 'card.Please enter Original' }) },
            ]}
          />
          <ProFormText.Password
            width={'md'}
            name="newPassword"
            label={intl.formatMessage({ id: 'card.New password' })}
            placeholder={intl.formatMessage({ id: 'card.Please enter New' })}
            rules={[
              { required: true, message: intl.formatMessage({ id: 'card.Please enter New' }) },
              {
                pattern: new RegExp(/^(?=.*[a-zA-Z])(?=.*\d).{6,16}$/),
                message: intl.formatMessage({ id: 'card.length' }),
              },
            ]}
          />
          <ProFormText.Password
            width={'md'}
            name="confirmPassword"
            label={intl.formatMessage({ id: 'card.Confirm Password' })}
            placeholder={intl.formatMessage({ id: 'card.confirmation' })}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'card.confirmation' }),
              },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('newPassword') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(
                    new Error(intl.formatMessage({ id: 'card.two passwords' })),
                  );
                },
              }),
            ]}
          />
        </div>
      </ModalForm>
      <Modal
        open={AppisModalOpen}
        width={890}
        onOk={handleOk}
        onCancel={handleCancel}
        footer={null}
      >
        <p></p>
        <div className="Bigdiv">
          {/* <div className="Icon">
            <AndroidOutlined style={{ fontSize: '100px' }} />
            <p></p>
            <p className='fontSize'>此APP在紧急情况下使用</p>
            <button className='ButtonDown'
              onClick={() => {
                downloadFile(downObj.app_url, downObj.app_name)
              }}
            >APP下载</button>
          </div> */}
          <div className="Icon">
            <AlertOutlined style={{ fontSize: '100px' }} />

            <p></p>
            <p className="fontSize">{intl.formatMessage({ id: 'card.circumstances.' })}</p>
            <button
              className="ButtonDown"
              onClick={() => {
                downloadFile(downObj.emergency_soft, downObj.emergency_soft_name);
              }}
            >
              {intl.formatMessage({ id: 'card.Emergency Software' })}
            </button>
          </div>
          <div className="Icon">
            <PaperClipOutlined style={{ fontSize: '100px' }} />

            <p></p>
            <p className="fontSize">{intl.formatMessage({ id: "card.Installation download" })}</p>
            <button
              className="ButtonDown"
              onClick={() => {
                downloadFile(downObj.driver_url, downObj.driver_name); // 下载文件的路径
              }}
            >
              {intl.formatMessage({ id: 'card.Driver download' })}
            </button>
          </div>
        </div>
      </Modal>
    </>
  );
};

export default AvatarDropdown;
